package com.qh.resourcehub.program.file;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class UploadController {

    // 上传文件保存路径
    private static final String UPLOAD_DIR = "/home/dataFile/";

    @PostMapping("/attachment")
    public Map<String, Object> uploadAttachment(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        if (file.isEmpty()) {
            result.put("retCode", 400);
            result.put("retMsg", "上传文件为空");
            return result;
        }
        try {
            // 创建保存目录
            File dir = new File(UPLOAD_DIR);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            // 获取文件名 + 后缀
            String originalFileName = file.getOriginalFilename();
//            String fileExt = originalFileName.substring(originalFileName.lastIndexOf("."));
//            String newFileName = UUID.randomUUID() + fileExt;

            // 目标文件
            File dest = new File(dir, originalFileName);
            file.transferTo(dest); // 保存到磁盘
            // 拼接可访问 URL（假设你配置了静态资源映射）
            String accessUrl = UPLOAD_DIR + originalFileName;
            result.put("retCode", 1001);
            result.put("retMsg", "上传成功");
            result.put("fileUrl", accessUrl);
        } catch (IOException e) {
            result.put("retCode", 1002);
            result.put("retMsg", "上传失败：" + e.getMessage());
        }
        return result;
    }
}
